package com.km.gulimall.product.web;


import com.km.gulimall.product.entity.CategoryEntity;
import com.km.gulimall.product.service.CategoryService;
import com.km.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Controller
public class IndexController {

    @Autowired
    CategoryService categoryService;

    @Autowired
    RedissonClient redisson;


    @GetMapping({"/","index.html"})
    public String indexPage(Model model){

        //1、查出所有的一级分类
        List<CategoryEntity> categoryEntities = categoryService.getLevel1Categorys();
        model.addAttribute("categories",categoryEntities);

        return "index";
    }

    //"index/catalog.json"
    @GetMapping(value = "/index/catalog.json")
    @ResponseBody
    public Map<String, List<Catelog2Vo>> getCatalogJson() {

        Map<String, List<Catelog2Vo>> catalogJson = categoryService.getCatalogJson();

        return catalogJson;

    }

    @ResponseBody
    @GetMapping("/hello")
    public String hello(){
        //获取一把锁,只要锁的名字一样,就是同一把锁
        RLock lock = redisson.getLock("my-lock");

        //加锁

        lock.lock(); //阻塞式等待   默认加的锁都是30s时间(看门狗机制)
        lock.lock(10, TimeUnit.SECONDS);  //设置时间10s后自动解锁,自动解锁的时间一定要大于业务执行时间  无看门狗机制
        //1)锁的自动续期,如果业务超长,运行期间自动给锁续上新的30s.不用担心业务过长,锁自动过期被删掉
        //2)加锁的业务只要运行完成,就不会给当前续期,即使不手动解锁,锁默认30s以后自动删除

        //最佳实战
        //1)还是推荐 lock.lock(30, TimeUnit.SECONDS);省掉了整个续期的操作,手动解锁
        try {
            System.out.println("加锁成功,执行业务"+Thread.currentThread().getId());
            Thread.sleep(30000);
        }catch (Exception e) {

        } finally{
            //解锁
            System.out.println("释放锁..."+Thread.currentThread().getId());
            lock.unlock();
        }

        return "hello";
    }
}
